package com.itheima.comfyui.core.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.itheima.comfyui.client.pojo.ComfyuiModel;
import com.itheima.comfyui.client.pojo.ComfyuiRequestDto;
import com.itheima.comfyui.client.pojo.ComfyuiTask;
import com.itheima.comfyui.core.dto.request.Text2ImageResDto;
import com.itheima.comfyui.core.service.FreemarkerService;
import com.itheima.comfyui.core.service.OllamaService;
import com.itheima.comfyui.core.service.Text2ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class Text2ImageServiceImpl implements Text2ImageService {
    public static final String COMFYUI_CLIENT_ID = "star-graph";
    @Autowired
    private OllamaService ollamaService;
    @Autowired
    private FreemarkerService freemarkerService;


    /**
     * 获取任务
     * @param text2ImageResDto
     * @return
     */
    @Override
    public ComfyuiTask getComfyuiTask(Text2ImageResDto text2ImageResDto) throws Exception {
        ComfyuiModel model = new ComfyuiModel();
        //封装基本信息
        model.setSize(text2ImageResDto.getSize());
        model.setStep(text2ImageResDto.getStep());
        model.setCfg(text2ImageResDto.getCfg());
        model.setWidth(text2ImageResDto.width());
        model.setHeight(text2ImageResDto.height());
        model.setModelName(text2ImageResDto.modelName());
        model.setSamplerName(text2ImageResDto.samplerName());
        model.setScheduler(text2ImageResDto.scheduler());
        model.setSeed(text2ImageResDto.getSeed());
        //正向提示词
        model.setPropmt(String.format("(8k, best quality, masterpiece),(high detailed skin),%s",ollamaService.translate(text2ImageResDto.getPropmt())));
        //负向提示词
        if(StrUtil.isNotEmpty(text2ImageResDto.getReverse())){
            model.setReverse(ollamaService.translate(model.getReverse()));
        }
        //默认负向提示词
        model.setReverse(String.format("%s,bad face,naked,bad finger,bad arm,bad leg,bad eye", model.getReverse()));
        //配置模板


        String s = freemarkerService.renderText2Image(model);
        ComfyuiRequestDto dto = new ComfyuiRequestDto(COMFYUI_CLIENT_ID, JSON.parseObject(s));
        ComfyuiTask task = new ComfyuiTask(text2ImageResDto.getClientId(), dto);
        return task;
    }
}
